﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using libtcod;

namespace CSRoguelike
{
    class Game
    {
        private const int ScreenWidth = 80;
        private const int ScreenHeight = 50;
        private const int MapWidth = 80;
        private const int MapHeight = 45;
        private const int LIMIT_FPS = 20;
        private bool IsRunning;

        private List<Actor> actors;
        private Actor player;
        private Map map;
        public Game()
        {
            actors = new List<Actor>();
            player = new Actor(ScreenWidth / 2, ScreenHeight / 2, '@', TCODColor.white);
            actors.Add(player);
            map = new Map(MapWidth, MapHeight, ref player);
        }

        public void HandleKeys()
        {
            TCODKey key = TCODConsole.checkForKeypress();
            if (TCODConsole.isKeyPressed(TCODKeyCode.Up))
            {
                if (map.IsValid(player.X, player.Y - 1)) player.Move(0, -1);
            }
            if (TCODConsole.isKeyPressed(TCODKeyCode.Down))
            {
                if (map.IsValid(player.X, player.Y + 1)) player.Move(0, 1);
            }
            if (TCODConsole.isKeyPressed(TCODKeyCode.Left))
            {
                if (map.IsValid(player.X - 1, player.Y)) player.Move(-1, 0);
            }
            if (TCODConsole.isKeyPressed(TCODKeyCode.Right))
            {
                if (map.IsValid(player.X + 1, player.Y)) player.Move(1, 0);
            }
            if (TCODConsole.isKeyPressed(TCODKeyCode.Escape))
                IsRunning = false;
        }

        public void Start()
        {
            libtcod.TCODConsole.initRoot(ScreenWidth, ScreenHeight, "Roguelike");
            TCODSystem.setFps(LIMIT_FPS);
            IsRunning = true;

            TCODConsole con = new TCODConsole(ScreenWidth, ScreenHeight);

            while (!TCODConsole.isWindowClosed() && IsRunning)
            {
                foreach (Actor a in actors)
                {
                    a.Draw(con);
                }
                map.Render(con);                

                TCODConsole.blit(con, 0, 0, ScreenWidth, ScreenHeight, TCODConsole.root, 0, 0);
                TCODConsole.flush();

                foreach (Actor a in actors)
                {
                    a.Clear(con);
                }

                HandleKeys();
            }
        }
    }
}
